<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-04-24
 * Time: 10:49:07
 * Info:
 */

namespace app\common\model;

use think\facade\Db;
use Casbin\WebmanPermission\Permission;

class AuthGroup extends Common
{

    public static function getInfo($id)
    {
        $info = AuthGroup::where('id', $id)->find();
        if (empty($info)) {
            return ['code' => 0, 'msg' => '获取信息失败'];
        }
        if (is_object($info)) {
            $info = $info->toArray();
        }

        return ['code' => 200, 'msg' => '获取信息成功', 'data' => $info];
    }

    public static function manageAdd($param)
    {
        if (is_array($param['rules'])) {
            $param['rules'] = implode(',', $param['rules']);
        }
        $authGroup = AuthGroup::create($param);
        self::addCasbinRule($authGroup->id, $param['rules']);

        return ['code' => 200, 'msg' => '添加成功'];
    }

    public static function manageEdit($param)
    {
        if (is_array($param['rules'])) {
            $param['rules'] = implode(',', $param['rules']);
        }
        //判断是否id=1
        if ($param['id'] === 1) {
            return ['code' => 0, 'msg' => '禁止修改超级管理员'];
        }
        //查询id是否存在
        $findData = AuthGroup::where('id', $param['id'])->find();
        if (empty($findData)) {
            return ['code' => 0, 'msg' => '该角色组不存在'];
        }
        $where = ['id' => $param['id']];
        AuthGroup::update($param, $where);
        self::addCasbinRule($param['id'], $param['rules']);

        return ['code' => 200, 'msg' => '修改成功'];
    }

    public static function manageDelete($id)
    {
        $findGroup = AuthGroup::where('id', $id)->find();
        if (empty($findGroup)) {
            return ['code' => 0, 'msg' => '该角色组信息不存在'];
        }
        //判断此角色组下是否有管理员
        $findAdmin = Admin::where('role_id', $id)->select()->toArray();
        if ( ! empty($findAdmin)) {
            return ['code' => 0, 'msg' => '请先删除该角色组下的管理员'];
        }
        AuthGroup::destroy($id);
        self::addCasbinRule($id, '');

        return ['code' => 200, 'msg' => '删除成功'];
    }

    public static function getGroupName()
    {
        $listName = AuthGroup::where(['status' => 1])->column('name', 'id');

        return $listName;
    }

    /**
     * 写入casbin_rule 表规则
     *
     * @param $role_id
     * @param $rule_id
     *
     * @return void
     */
    public static function addCasbinRule($role_id, $rule_id = '')
    {
        if (empty($role_id)) {
            return;
        }
        //先删除对应角色的权限
        Permission::deleteRole('admin_role_'.$role_id);

        $ruleIdArr = array_filter(explode(',', $rule_id));
        if (empty($ruleIdArr)) {
            return;
        }
        $data = [];
        //获取pid=0的菜单，并追加
        $authMenu = AuthMenu::where('pid', 0)->column('node');
        foreach ($authMenu as $a) {
            $sub = 'admin_role_'.$role_id;
            $act = "GET";

            $data1['ptype'] = 'p';
            $data1['v0']    = $sub;
            $data1['v1']    = $a;
            $data1['v2']    = $act;
            $data[]         = $data1;
        }
        Db::table('casbin_rule')->insertAll($data);

        $data2     = [];
        $authRules = AuthRule::whereIn('id', $ruleIdArr)->column('node', 'id');
        foreach ($ruleIdArr as $rule) {
            $sub     = 'admin_role_'.$role_id;
            $obj     = ! empty($authRules[$rule]) ? $authRules[$rule] : '';
            $act     = "GET";
            $data2[] = [$sub, $obj, $act];
        }
        Permission::addPolicies($data2);
    }

    /**
     * 2022-08-02
     * 旧版规则添加（使用Db的方式）
     * 问题：验证权限时候，必须同时使用db的方式
     *
     * @param $role_id
     * @param $rule_id
     *
     */
    public static function addCasbinRuleOld($role_id, $rule_id = '')
    {
        if (empty($role_id)) {
            return;
        }
        //先删除对应角色的权限
        Db::table('casbin_rule')->where('v0', 'admin_role_'.$role_id)->delete();

        $ruleIdArr = explode(',', $rule_id);

        if (empty($ruleIdArr)) {
            return;
        }
        $data = [];
        //获取pid=0的菜单，并追加
        $authMenu = AuthMenu::where('pid', 0)->column('node');
        foreach ($authMenu as $a) {
            $sub = 'admin_role_'.$role_id;
            $act = "GET";

            $data1['ptype'] = 'p';
            $data1['v0']    = $sub;
            $data1['v1']    = $a;
            $data1['v2']    = $act;
            $data[]         = $data1;
        }
        $authRules = AuthRule::whereIn('id', $ruleIdArr)->column('node', 'id');
        foreach ($ruleIdArr as $rule) {
            $sub         = 'admin_role_'.$role_id;
            $obj         = ! empty($authRules[$rule]) ? $authRules[$rule] : '';
            $act         = "GET";
            $data1['v0'] = $sub;
            $data1['v1'] = $obj;
            $data1['v2'] = $act;
            $data[]      = $data1;
        }
        Db::table('casbin_rule')->insertAll($data);
    }

}
